<template>
  <view class="sticky-container">
    <!-- 吸顶内容容器 -->
    <view 
      ref="stickyContent"
      :class="['sticky-content', isSticky ? 'sticky-active' : '']"
    >
      <slot></slot>
    </view>
    <!-- 占位元素 -->
    <view :style="{ height: isSticky ? contentHeight + 'px' : '0' }" class="sticky-placeholder"></view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { onPageScroll } from '@dcloudio/uni-app'

// Props
const props = defineProps({
  // 吸顶触发阈值(px)，默认0
  threshold: {
    type: Number,
    default: 0
  },
  // 是否显示占位元素
  showPlaceholder: {
    type: Boolean,
    default: true
  }
})

// Refs
const stickyContent = ref<HTMLElement | null>(null)
const contentHeight = ref(0)
const isSticky = ref(false)
let scrollTop = ref(0)

// 滚动监听处理函数
const handleScroll = (e:any) => {

  scrollTop.value = e.scrollTop
  isSticky.value = scrollTop.value >= props.threshold
}

onMounted(() => {
  // 获取内容高度
  nextTick(() => {
    if (stickyContent.value) {
      const rect = uni.createSelectorQuery().select('.sticky-content').boundingClientRect()
      rect.exec(data => {
        if (data && data[0]) {
          contentHeight.value = data[0].height
        }
      })
    }
  })
  // 注册滚动监听
  onPageScroll(handleScroll)
})

onUnmounted(() => {
  // 移除滚动监听（UniApp的onPageScroll无法直接解绑，这里使用标志位间接处理）
  // 实际项目中可使用事件总线或第三方库实现更完善的解绑
})
</script>

<style lang="scss" scoped>
.sticky-container {
  width: 100%;
}

.sticky-content {
  width: 100%;
  transition: all 0.3s ease;
}

.sticky-active {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  // 可根据需要添加默认背景色
  // background-color: #fff;
  // box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  
}

.sticky-placeholder {
  transition: height 0.3s ease;
}
</style>